<template>
  <!-- 分配权限的弹层 -->
  <el-dialog
    title="分配权限(一级为路由页面查看权限-二级为按钮操作权限)"
    :visible="showAssignDialog"
    @close="closeAssignDialog"
  >
    <!-- 权限点数据展示 -->
    <!-- node-key 每个树节点用来作为唯一标识的属性， -->
    <el-tree
      ref="tree"
      :data="permList"
      node-key="id"
      :props="{ label: 'name' }"
      default-expand-all
      show-checkbox
      check-strictly
    />

    <template #footer>
      <el-button @click="closeAssignDialog">取消</el-button>
      <el-button type="primary" @click="savePerm">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getPermissionList } from '@/api/permisson'
import { transformTreeData } from '@/utils'
// 导入回显的接口
import { getRoleDetail } from '@/api/setting'
// 添加权限
import { assignPerm } from '@/api/setting'
export default {
  props: {
    showAssignDialog: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      permList: [],
      permId: '' // 存储id
    }
  },
  created () {
    this.getPermList()
  },
  methods: {
    // 保存选中的权限点
    async savePerm () {
      //  getCheckedKeys获取树中被选中权限点
      await assignPerm({ id: this.permId, permIds: this.$refs.tree.getCheckedKeys() })
      this.$message.success('操作成功')
      this.$emit('update:showAssignDialog', false)
    },
    // 回显分配过的权限点
    async getPerm (id) {
      this.permId = id
      const data = await getRoleDetail(id)
      // console.log(data)
      // 调用树组件的方法回显.必须和node-key="id"一起出现
      this.$refs.tree.setCheckedKeys(data.permIds)
    },
    // 获取权限列表
    async getPermList () {
      const data = await getPermissionList()
      // console.log(data)
      this.permList = transformTreeData(data)
    },
    // 关闭弹出层
    closeAssignDialog () {
      // 重置选值为空
      this.$refs.tree.setCheckedKeys([])
      this.$emit('update:showAssignDialog', false)
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
